package com.xcc.common;

import com.xcc.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @outhor Ren
 * @create 2019-03-21 23:25
 * 描述:
 * Http 请求前后监听工具
 */
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {

    private final static String START_TIME = "startTime";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 请求前获取参数

        // 记录请求时间
        long startTime = System.currentTimeMillis();
        request.setAttribute(START_TIME, startTime);

        String url = request.getRequestURI().toString();
        Map parameterMap = request.getParameterMap();
        log.info("request start. url:{}, params:{}", url, JsonMapper.obj2String(parameterMap));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        // 请求完成后调用
        String url = request.getRequestURI().toString();
        Map parameterMap = request.getParameterMap();

        // 记录请求时间
        long startTime = (long) request.getAttribute(START_TIME);
        long endTime = System.currentTimeMillis();

        log.info("request finished. url:{}, params:{}, cost: {}", url, JsonMapper.obj2String(parameterMap), (endTime - startTime));
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        // 结束后调用
        String url = request.getRequestURI().toString();
        Map parameterMap = request.getParameterMap();
        long startTime = (long) request.getAttribute(START_TIME);
        long endTime = System.currentTimeMillis();
        log.info("request exception. url:{}, params:{}, cost: {}", url, JsonMapper.obj2String(parameterMap), (endTime - startTime));
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}
